package com.sctvcloud.bazhong.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.beans.FCityItem;
import com.sctvcloud.bazhong.beans.FCityNews;
import com.sctvcloud.bazhong.beans.FCityState;
import com.sctvcloud.bazhong.beans.FScribeState;
import com.sctvcloud.bazhong.beans.FUsers;
import com.sctvcloud.bazhong.beans.NewsItem;
import com.sctvcloud.bazhong.http.AbsListNetCallback;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.http.ParamsEditor;
import com.sctvcloud.bazhong.ui.activities.CityStaHomepageActivity;
import com.sctvcloud.bazhong.ui.activities.LoginActivity;
import com.sctvcloud.bazhong.ui.adapter.CityStaChannelAdapter;
import com.sctvcloud.bazhong.ui.adapter.CityStateNewsAdapter;
import com.sctvcloud.bazhong.ui.utils.SkipUtil;
import com.sctvcloud.bazhong.utils.ListTypeUtils;
import com.sctvcloud.bazhong.utils.UserManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/17 0017.
 * 首页市州界面
 */
public class CityStateFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.city_state_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.city_state_channel_list)
    protected RecyclerView channel_list;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    @BindView(R.id.city_news_list)
    protected RecyclerView news_list;
    private LinearLayoutManager channelManager;
    private GridLayoutManager videoManager;
    private CityStaChannelAdapter channelAdapter;
    private CityStateNewsAdapter newsAdapter;
    private int currentNews = 0;
    private int pageAll = 0;
    private String newsUrl;
    private List<FCityState> cityList;
    private String token;
    private String userId;
    public static final int REQUEST_CODE = 1;
    public static final int REQUEST_LOGIN_CODE = 101;
    private boolean isSubscribe;
    private int types; //types 1 订阅 2取消订阅
    private String institutionId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_city_state, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        channelManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        channel_list.setItemAnimator(new DefaultItemAnimator());
        channel_list.setLayoutManager(channelManager);
        videoManager = new GridLayoutManager(getActivity(), 2);
        news_list.setItemAnimator(new DefaultItemAnimator());
        news_list.setLayoutManager(videoManager);
        detail.setiScrollView(this);
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        super.onFragmentShow(isFirst, isCallFromResume);
        if (isFirst) {
            refreshLayout.autoRefresh();
        }
        return true;
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentNews = currentNews + 1;
            if (currentNews < pageAll) {
                getCityStateDynamicList(newsUrl, currentNews);
            }
        }
    }

    @Override
    public void onRefresh() {
        getCityStateList();
    }

    /**
     * 获取市州机构列表
     */
    private void getCityStateList() {
        NetUtils.getNetAdapter().getStateList(getOwnerName(), channelUrl, new AbsNetCallBack<FCityItem>(FCityNews.class) {
            @Override
            public void onSuc(FCityItem fCityItem) {
                if (fCityItem != null) {
                    setStateData(fCityItem);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                onNetFinish();
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    /**
     * 获取机构新闻列表
     */
    private void getCityStateDynamicList(String newsUrl, int calledPage) {
        if (TextUtils.isEmpty(newsUrl)|| !newsUrl.endsWith(".json")) {
            toast("数据错误");
            return;
        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), newsUrl, calledPage, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), calledPage) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    pageAll = getPageResponse().getData().getPageAll();
                    currentNews = getPageResponse().getData().getPageIndex();
                    setNewsData(newsItems);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    /**
     * 获取用户订阅的机构
     */
    private void getsubcribeList() {
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
        }
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(userId)) {
            ParamsEditor pe = new ParamsEditor();
            pe.put("userId", userId);
//            ArrayMap<String, Object> params = new ArrayMap<>();
//            params.put("token", token);
//            params.put("userId", userId);
            NetUtils.getNetAdapter().getUserOrganList(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsListNetCallback<FCityState>(ListTypeUtils.FCityState()) {
                        @Override
                        public void onSuc(List<FCityState> fCityStates) {
                            if (ListUtils.isListValued(fCityStates)) {
                                if (ListUtils.isListValued(cityList)) {
                                    compareSubscribe(cityList, fCityStates);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
//                            toast(errorMsg);
                        }
                    });
        } else {
            JLog.e("====" + "你还没有登录");
        }
    }

    /**
     * 订阅或取消订阅某个机构数据
     * @param cityState
     */
    private void getSubscribeStateChange(final FCityState cityState) {
        if (cityState == null) {
            return;
        }
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
            isSubscribe = cityState.isSubscribe();
            institutionId = cityState.getInstitutionId();
            if (isSubscribe) {
                types = 2;
            } else {
                types = 1;
            }
            ParamsEditor pe = new ParamsEditor();
//            pe.put("userId", userId);
//            ArrayMap<String, Object> params = new ArrayMap<>();
            pe.put("institutionId", institutionId);
            pe.put("type", types); //1订阅 2 取消订阅
            pe.put("userId", userId);
            NetUtils.getNetAdapter().getSubscribeState(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsNetCallBack<FScribeState>(FScribeState.class) {
                        @Override
                        public void onSuc(FScribeState scribeState) {
                            isSubscribe = !isSubscribe;
                            // cityState.setSubscibe(isSubscribe);
                            for (int i = 0; i < cityList.size(); i++) {
                                FCityState fCityState = cityList.get(i);
                                if (cityState.getInstitutionId().equals(fCityState.getInstitutionId())) {
                                    fCityState.setSubscibe(isSubscribe);
                                    if (types == 1) {
                                        fCityState.setType(1);
                                    } else if (types == 2) {
                                        fCityState.setType(0);
                                    }

                                }
                            }
                            Collections.sort(cityList);
                            if (channelAdapter != null) {
                                channelAdapter.setData(cityList);
                            }
                            // channelAdapter.notifyDataSetChanged();
                            //getSubscribeState(isSubscribe);

                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            JLog.e("====error=" + errorMsg);
                            toast(errorMsg);
                        }
                    });

        } else {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN_CODE);
        }

    }

    /**
     * 加载市州媒体列表
     * @param fCityItem
     */
    private void setStateData(FCityItem fCityItem) {
        cityList = fCityItem.getInstitutionList();
        newsUrl = fCityItem.getInstitutionDynamicList();
        getCityStateDynamicList(newsUrl, 0);
        if (ListUtils.isListValued(cityList)) {
            getsubcribeList();
            Collections.sort(cityList);
            if (channelAdapter == null) {
                channelAdapter = new CityStaChannelAdapter(getActivity(), cityList).setItemInternalClick(channelItemClick);
                channelAdapter.setOnSubscribeClick(subsceibeClick);
                channel_list.setAdapter(channelAdapter);
            } else {
                channelAdapter.setData(cityList);
            }
        }

    }

    /**
     * 加载新闻数据列表
     * @param data
     */
    private void setNewsData(List<NewsItem> data) {
        if (newsAdapter == null) {
            newsAdapter = new CityStateNewsAdapter(getContext(), data).setItemInternalClick(newsItemClick);
            news_list.setAdapter(newsAdapter);
        }
        if (currentNews == 0) {
            newsAdapter.setData(data);
        } else {
            newsAdapter.addDatas(data);
        }
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(currentNews + 1 < pageAll);
    }

    /**
     * 对比那些机构已订阅，并刷新机构列表中的数据状态
     *
     * @param list
     * @param subList
     */
    private void compareSubscribe(List<FCityState> list, List<FCityState> subList) {
        for (int i = 0; i < list.size(); i++) {
            FCityState fCityState = list.get(i);
            String institutionId = fCityState.getInstitutionId();
            for (int j = 0; j < subList.size(); j++) {
                if (institutionId.equalsIgnoreCase(subList.get(j).getInstitutionId())) {
                    fCityState.setSubscibe(true);
                    fCityState.setType(1);
                }
            }
        }
        Collections.sort(list);
        if (channelAdapter != null) {
            channelAdapter.setData(list);
        }
    }

    OnItemInternalClick subsceibeClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FCityState item = channelAdapter.getItem(position);
            getSubscribeStateChange(item);
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "市州"));
            pairs.add(new Pair<>("位置", item.getInstitutionName()));
            if (item.isSubscibe()) {
                pairs.add(new Pair<>("行为类型", "取消订阅"));
            } else {
                pairs.add(new Pair<>("行为类型", "点击订阅"));
            }
            GridsumWebDissector.getInstance().trackEvent(CityStateFragment.this, "", item.getInstitutionName(), "", 200, pairs);


        }
    };

    OnItemInternalClick channelItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FCityState state = null;
            if (view == null) {
                state = (FCityState) itemView.getTag(R.id.adapter_item_data_key);
            } else {
                state = (FCityState) itemView.getTag(R.id.adapter_item_data_key);
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "市州"));
            pairs.add(new Pair<>("位置", state.getInstitutionName()));
            pairs.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(CityStateFragment.this, "", state.getInstitutionName(), "", 200, pairs);
            Intent intent = new Intent(getActivity(), CityStaHomepageActivity.class);
            intent.putExtra(BaseActivity.EX_ID, state.getInstitutionId());
            intent.putExtra(BaseActivity.EX_TITLE, state.getInstitutionName());
            intent.putExtra(CityStaHomepageActivity.CHANNEL_SUBSCRIBE, state.isSubscribe());
            intent.putExtra(CityStaHomepageActivity.HOT_TAG, state.getHotLevel());


            if (state.getInstitutionUrl().endsWith(".json")) {
                intent.putExtra(BaseActivity.EX_URL, state.getInstitutionUrl());
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                toast("数据错误");
            }


        }
    };
    OnItemInternalClick newsItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            NewsItem newsItem = null;
            if (view == null) {
                newsItem = (NewsItem) itemView.getTag(R.id.adapter_item_data_key);
            } else {
                newsItem = (NewsItem) itemView.getTag(R.id.adapter_item_data_key);
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "市州"));
            ArrayList<Pair<String, String>> pairsMap = new ArrayList<>();
            pairsMap.addAll(pairs);
            pairsMap.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(CityStateFragment.this, "", newsItem.getNewsTitle(), "", 200, pairsMap);
            HashMap<String, String> map = new HashMap<>();
            for (Pair<String, String> p : pairs) {
                map.put(p.first, p.second);
            }
            if (newsItem != null) {
                //进入相应的新闻详情页面
                SkipUtil.skipWithNewsItem(getContext(), newsItem, map);
            } else {
                toast("数据错误");
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            onRefresh();
        }
        if (requestCode == REQUEST_LOGIN_CODE) {
            onRefresh();
        }

    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        boolean b = ViewCompat.canScrollVertically(news_list, -1);
        JLog.e("ggag   " + b);
        return b;
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        boolean b = ViewCompat.canScrollVertically(news_list, 1);
        JLog.e("ggag   " + b);
        return b;
    }
}
